package com.changgou.search.controller;

import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import entity.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @author 秦川熙
 */
@Controller
@RequestMapping(value = "/search")
public class SkuController {

    @Autowired
    private SkuFeign skuFeign;

    @GetMapping(value = "/list")
    public String search(@RequestParam(required = false) Map<String, String> searchMap, Model model) {
        //调用changgou-search微服务
        Map<String, Object> resultMap = skuFeign.search(searchMap);
        //搜索数据结果
        model.addAttribute("result", resultMap);
        //搜索条件
        model.addAttribute("searchMap", searchMap);
        //请求地址
        String[] urls = url(searchMap);
        model.addAttribute("url", urls[0]);
        model.addAttribute("sorturl", urls[1]);
        //分页计算
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(resultMap.get("totalPages").toString()),
                Integer.parseInt(resultMap.get("pageNum").toString()),
                Integer.parseInt(resultMap.get("pageSize").toString())
        );
        model.addAttribute("page", page);
        //3.返回
        return "search";
    }

    private String[] url(Map<String, String> searchMap) {
        // a/b?id=1&
        String url = "/search/list";
        String sorturl = "/search/list";
        if (searchMap != null && searchMap.size() > 0) {
            url += "?";
            sorturl+="?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {

                if (entry.getKey().equalsIgnoreCase("pageNum")) {
                    continue;
                }

                //如果是排序 则 跳过 拼接排序的地址 因为有数据
                if(entry.getKey().equals("sortField") || entry.getKey().equals("sortRule")){
                    continue;
                }
                url += entry.getKey() + "=" + entry.getValue() + "&";

            }
            if(url.lastIndexOf("&")!=-1) {
                url = url.substring(0, url.lastIndexOf("&"));
            }
            url = url.substring(0, url.length() - 1);
            sorturl = sorturl.substring(0, sorturl.length() - 1);
        }
        return new String[]{url, sorturl};
    }
}
